<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/Peppa.png?v=7.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/Peppa.jpg?v=7.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/Peppa.jpg?v=7.0.0">








<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="1 前言1.1 什么是动态规划动态规划（Dynamic Programming）是求解决策过程最优化的数学方法。把多阶段过程转化为一系列单阶段问题，利用各阶段之间的关系，逐个求解，创立了解决这类过程优化问题的新方法——动态规划。 1.2 什么时候要用动态规划如果要求一个问题的最优解（通常是最大值或者最小值），而且该问题能够分解成若干个子问题，并且小问题之间也存在重叠的子问题，则考虑采用动态规划。">
<meta name="keywords" content="ACM,动态规划">
<meta property="og:type" content="article">
<meta property="og:title" content="ACM动态规划基础篇">
<meta property="og:url" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/index.html">
<meta property="og:site_name" content="linxi&#39;s dream">
<meta property="og:description" content="1 前言1.1 什么是动态规划动态规划（Dynamic Programming）是求解决策过程最优化的数学方法。把多阶段过程转化为一系列单阶段问题，利用各阶段之间的关系，逐个求解，创立了解决这类过程优化问题的新方法——动态规划。 1.2 什么时候要用动态规划如果要求一个问题的最优解（通常是最大值或者最小值），而且该问题能够分解成若干个子问题，并且小问题之间也存在重叠的子问题，则考虑采用动态规划。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p1.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p2.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p3.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p4.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p5.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p6.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p7.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p8.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p9.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p10.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p11.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p12.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p13.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p14.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p15.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p16.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p17.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p18.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p19.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p20.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p21.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p22.png">
<meta property="og:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p23.png">
<meta property="og:updated_time" content="2019-11-27T12:00:44.098Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ACM动态规划基础篇">
<meta name="twitter:description" content="1 前言1.1 什么是动态规划动态规划（Dynamic Programming）是求解决策过程最优化的数学方法。把多阶段过程转化为一系列单阶段问题，利用各阶段之间的关系，逐个求解，创立了解决这类过程优化问题的新方法——动态规划。 1.2 什么时候要用动态规划如果要求一个问题的最优解（通常是最大值或者最小值），而且该问题能够分解成若干个子问题，并且小问题之间也存在重叠的子问题，则考虑采用动态规划。">
<meta name="twitter:image" content="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/p1.png">






  <link rel="canonical" href="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>ACM动态规划基础篇 | linxi's dream</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b4099cd89c9f33abab06a03748dac801";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">linxi's dream</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">穷且益坚，不坠青云之志</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://linxi99.gitee.io/20190211/ACM动态规划基础篇/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="linxi">
      <meta itemprop="description" content="stay hungry, stay foolish">
      <meta itemprop="image" content="/images/star.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="linxi's dream">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ACM动态规划基础篇

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-02-11 16:40:28" itemprop="dateCreated datePublished" datetime="2019-02-11T16:40:28+08:00">2019-02-11</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-11-27 20:00:44" itemprop="dateModified" datetime="2019-11-27T20:00:44+08:00">2019-11-27</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/DP一般看规律/" itemprop="url" rel="index"><span itemprop="name">DP一般看规律</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/20190211/ACM动态规划基础篇/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/20190211/ACM动态规划基础篇/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/20190211/ACM动态规划基础篇/" class="leancloud_visitors" data-flag-title="ACM动态规划基础篇">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
            <span class="post-meta-divider">|
            </span> <span title="post.wordcount">
            <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
            </span>字数： 3.7k
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1-前言"><a href="#1-前言" class="headerlink" title="1 前言"></a>1 前言</h1><h2 id="1-1-什么是动态规划"><a href="#1-1-什么是动态规划" class="headerlink" title="1.1 什么是动态规划"></a>1.1 什么是动态规划</h2><p>动态规划（Dynamic Programming）是求解决策过程最优化的数学方法。把多阶段过程转化为一系列单阶段问题，利用各阶段之间的关系，逐个求解，创立了解决这类过程优化问题的新方法——动态规划。</p>
<h2 id="1-2-什么时候要用动态规划"><a href="#1-2-什么时候要用动态规划" class="headerlink" title="1.2 什么时候要用动态规划"></a>1.2 什么时候要用动态规划</h2><p>如果要求一个问题的最优解（通常是最大值或者最小值），而且该问题能够分解成若干个子问题，并且小问题之间也存在重叠的子问题，则考虑采用动态规划。</p>
<p>能采用动态规划求解的问题的一般要具有3个性质：</p>
<ul>
<li>最优化原理<br>如果问题的最优解所包含的子问题的解也是最优的，就称该问题具有最优子结构，即满足最优化原理。</li>
<li>无后效性<br>即某阶段状态一旦确定，就不受这个状态以后决策的影响。也就是说，某状态以后的过程不会影响以前的状态，只与当前状态有关。</li>
<li>有重叠子问题<br>即子问题之间是不独立的，一个子问题在下一阶段决策中可能被多次使用到。（该性质并不是动态规划适用的必要条件，但是如果没有这条性质，动态规划算法同其他算法相比就不具备优势）</li>
</ul>
<a id="more"></a>
<h1 id="2-斐波那契数列-Fibonacci"><a href="#2-斐波那契数列-Fibonacci" class="headerlink" title="2 斐波那契数列 $Fibonacci$"></a>2 斐波那契数列 $Fibonacci$</h1><h2 id="2-1-引入"><a href="#2-1-引入" class="headerlink" title="2.1 引入"></a>2.1 引入</h2><p>有一头母牛，它每年年初生一头小母牛。每头小母牛从第二个年头开始，每年年初也生一头小母牛。请问在第n年的时候，共有多少头母牛？</p>
<h2 id="2-2-定义"><a href="#2-2-定义" class="headerlink" title="2.2 定义"></a>2.2 定义</h2><p>$fib(n) = fib(n - 1) + fib(n - 2)$</p>
<p>$0$ $1$ $1$ $2$ $3$ $5$ $8$ $13$ $21$ $34$</p>
<h2 id="2-3-递归分治解决-Recursion"><a href="#2-3-递归分治解决-Recursion" class="headerlink" title="2.3 递归分治解决 $Recursion$"></a>2.3 递归分治解决 $Recursion$</h2><h3 id="2-3-1-代码"><a href="#2-3-1-代码" class="headerlink" title="2.3.1 代码"></a>2.3.1 代码</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">fib</span><span class="params">(n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (n &lt; <span class="number">2</span>) ? n : fib(n - <span class="number">1</span>) + fib(n - <span class="number">2</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">fib</span><span class="params">(n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(n &lt; <span class="number">2</span>) <span class="keyword">return</span> n;</span><br><span class="line">    <span class="keyword">return</span> fib(n - <span class="number">1</span>) + fib(n - <span class="number">2</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-3-2-时间复杂度分析"><a href="#2-3-2-时间复杂度分析" class="headerlink" title="2.3.2 时间复杂度分析"></a>2.3.2 时间复杂度分析</h3><p><img src="/20190211/ACM动态规划基础篇/p1.png" alt="斐波那契数列递归求解"></p>
<p>$T(n) = T(n - 1) + T(n - 2) + 1 \gt 2 \cdot T(n - 2) + 1 = O((\sqrt{2})^n)$</p>
<p>$T(n) = T(n - 1) + T(n - 2) + 1 = O(fib(n)) = O(\varPhi ^ n)$ </p>
<script type="math/tex; mode=display">\varPhi = \frac{1 + \sqrt{5}}{2} = 1.618...</script><script type="math/tex; mode=display">\varPhi^{36} \approx 2^{25}</script><script type="math/tex; mode=display">\varPhi^{5} \approx 10</script><p><img src="/20190211/ACM动态规划基础篇/p2.png" alt="凉了呀"></p>
<h2 id="2-4-解决方案"><a href="#2-4-解决方案" class="headerlink" title="2.4 解决方案"></a>2.4 解决方案</h2><p>刚刚递归算法的不足之处在于重复计算了大量相同的子问题，浪费了大量时间</p>
<p><img src="/20190211/ACM动态规划基础篇/p3.png" alt="大量重复子问题"></p>
<p>好记性不如烂笔头</p>
<p>记忆化搜索$Memoization$</p>
<p>备忘录 $Look-up$ $Table$ $\to$ $Array$</p>
<p>用一个数组记录需要重复计算的子问题</p>
<p>这就是动态规划的第一种实现方式，也是最容易理解的写法：记忆化搜索</p>
<h2 id="2-5-记忆化搜索"><a href="#2-5-记忆化搜索" class="headerlink" title="2.5 记忆化搜索"></a>2.5 记忆化搜索</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> maxn = <span class="number">1e6</span> + <span class="number">5</span>;</span><br><span class="line"><span class="keyword">int</span> f[maxn];</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="built_in">memset</span>(f, <span class="number">-1</span>, <span class="keyword">sizeof</span>(f));</span><br><span class="line">    f[<span class="number">0</span>] = <span class="number">0</span>;</span><br><span class="line">    f[<span class="number">1</span>] = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">fib</span><span class="params">(n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>&amp; ret = f[n]</span><br><span class="line">    <span class="keyword">if</span>(ret != <span class="number">-1</span>) <span class="keyword">return</span> ret;</span><br><span class="line">    ret = fib(n - <span class="number">1</span>) + fib(n - <span class="number">2</span>);</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="/20190211/ACM动态规划基础篇/p4.png" alt="记忆化搜索后的计算过程"></p>
<h1 id="3-快速幂"><a href="#3-快速幂" class="headerlink" title="3 快速幂"></a>3 快速幂</h1><h2 id="3-1-问题描述"><a href="#3-1-问题描述" class="headerlink" title="3.1 问题描述"></a>3.1 问题描述</h2><script type="math/tex; mode=display">a^{98765} = ???</script><h2 id="3-2-十进制快速幂"><a href="#3-2-十进制快速幂" class="headerlink" title="3.2 十进制快速幂"></a>3.2 十进制快速幂</h2><script type="math/tex; mode=display">a^{9\cdot10^4 + 8\cdot10^3 + 7\cdot10^2 + 6\cdot10^1 + 5\cdot10^0}</script><p><img src="/20190211/ACM动态规划基础篇/p5.png" alt="十进制的快速幂"></p>
<script type="math/tex; mode=display">(a^{10^4})^9 \cdot (a^{10^3})^8 \cdot (a^{10^2})^7 \cdot (a^{10^1})^6 \cdot (a^{10^0})^5</script><h2 id="3-3-二进制快速幂"><a href="#3-3-二进制快速幂" class="headerlink" title="3.3 二进制快速幂"></a>3.3 二进制快速幂</h2><p>根据计算机的储存特性，我们可以通过以二进制的快速幂来节省代码量，以及加快运算速度</p>
<p><img src="/20190211/ACM动态规划基础篇/p6.png" alt="二进制的快速幂"></p>
<h2 id="3-4-代码实现"><a href="#3-4-代码实现" class="headerlink" title="3.4 代码实现"></a>3.4 代码实现</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ll <span class="title">quick_pow</span><span class="params">(ll a, ll b, ll mod)</span></span>&#123;</span><br><span class="line">    ll ret = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span>(b)&#123;</span><br><span class="line">        <span class="keyword">if</span>(b&amp;<span class="number">1</span>) ret = (ret*a)%mod;</span><br><span class="line">        a = (a*a)%mod;</span><br><span class="line">        b &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="4-最短向上路径问题"><a href="#4-最短向上路径问题" class="headerlink" title="4 最短向上路径问题"></a>4 最短向上路径问题</h1><h2 id="4-1-问题描述"><a href="#4-1-问题描述" class="headerlink" title="4.1 问题描述"></a>4.1 问题描述</h2><p>SPU(Shortest Path Upward)</p>
<p><img src="/20190211/ACM动态规划基础篇/p7.png" alt="SPU"></p>
<p>在某一个非负整数构成的$n \times m$矩阵中，找出从最底层通往最高层的一条路径，使得路径总长（沿途所经整数的总和）最小（你只能走到上一层离你当前位置最近的三个位置）</p>
<h2 id="4-2-暴力？"><a href="#4-2-暴力？" class="headerlink" title="4.2 暴力？"></a>4.2 暴力？</h2><p>如果直接暴力枚举所有的路径</p>
<p>分析一下，时间复杂度大概是$O(n\cdot3^m)$</p>
<p>可能，不太行</p>
<h2 id="4-3-递归分治VS动态规划"><a href="#4-3-递归分治VS动态规划" class="headerlink" title="4.3 递归分治VS动态规划"></a>4.3 递归分治VS动态规划</h2><h3 id="4-3-1-递归分治"><a href="#4-3-1-递归分治" class="headerlink" title="4.3.1 递归分治"></a>4.3.1 递归分治</h3><p>认真思考一下，发现可以这样递归来搞</p>
<script type="math/tex; mode=display">d^k(i) = w^k(i) + min\{d^{k - 1}(i - 1), d^{k - 1}(i), d^{k - 1}(i + 1)\}</script><p><img src="/20190211/ACM动态规划基础篇/p8.png" alt="递归分治"></p>
<h4 id="4-3-1-1-时间复杂度"><a href="#4-3-1-1-时间复杂度" class="headerlink" title="4.3.1.1 时间复杂度"></a>4.3.1.1 时间复杂度</h4><p>这样我们看似使用了非常优美的递归来解决问题，但请冷静下来分析一下时间复杂度</p>
<p><img src="/20190211/ACM动态规划基础篇/p9.png" alt="分析一波"></p>
<p>这样，我们会惊喜的发现：时间复杂度竟然和刚刚的暴力枚举算法是一样的</p>
<p>问题出现在哪里呢？</p>
<p>问题就出现在，我们重复计算了大量相同的问题，因此浪费了大量的时间</p>
<p>最高层的每一个位置我们只计算了一次，那么第二层平均每个会被上方的三个位置计算$3$次，以此类推，第三层每个位置便会计算$3^2$次…</p>
<p>如何解决呢？</p>
<h4 id="4-3-1-2-记忆化搜索"><a href="#4-3-1-2-记忆化搜索" class="headerlink" title="4.3.1.2 记忆化搜索"></a>4.3.1.2 记忆化搜索</h4><p>我们发现，每一个位置的最优情况，只和它的位置有关，而跟他的内部路线与接下来的选择无关，这就是我们所说的无后效性</p>
<p>这样的话，我们可以开一个$n\times m$的数组来储存所有位置的最优情况，然后将其初始化为$undifine$状态</p>
<p>只有当这个位置没有被计算过的时候，我们才需要继续递归分治解决这个子问题，否则的话，直接使用之前计算好并储存下来的结果就好</p>
<p>这样的话每一个位置至多会被计算一次，这时候我们会发现时间复杂度已经降到了$O(n*m)$</p>
<p><img src="/20190211/ACM动态规划基础篇/p10.png" alt="太秀了"></p>
<h3 id="4-3-2-正儿八经的动态规划"><a href="#4-3-2-正儿八经的动态规划" class="headerlink" title="4.3.2 正儿八经的动态规划"></a>4.3.2 正儿八经的动态规划</h3><h4 id="4-3-2-1-记忆化？"><a href="#4-3-2-1-记忆化？" class="headerlink" title="4.3.2.1 记忆化？"></a>4.3.2.1 记忆化？</h4><p>刚刚我们为什么需要记忆化呢</p>
<p>回想刚刚的问题，我们之所以需要递归分治并且记忆化的原因是：</p>
<p>我们需要的子问题的答案我们还没有计算出来</p>
<p>我们如何才能行云流水的推进过来，不需要询问没有解决的子问题呢</p>
<h4 id="4-3-2-2-动态规划"><a href="#4-3-2-2-动态规划" class="headerlink" title="4.3.2.2 动态规划"></a>4.3.2.2 动态规划</h4><p>我们考虑将刚才的过程颠倒过来</p>
<p>我们从底层往上层走：</p>
<p><img src="/20190211/ACM动态规划基础篇/p11.png" alt="动态规划"><br>考虑dp转移式</p>
<script type="math/tex; mode=display">dp[k][i] = w[k][i] + min\{dp[k - 1][i - 1] + dp[k - 1][i] + dp[k - 1][i + 1]\}</script><p>这样从底层往上层推进，我们会惊喜的发现，当我们推进到第$i$层的时候，第$i - 1$层的所有子问题都已经解决并且记录下了</p>
<p>而且我们发现每次只需要上一层的数据，并不需要再之前的所有子问题，我们还可以考虑滚动数组来降低空间复杂度</p>
<p><img src="/20190211/ACM动态规划基础篇/p12.png" alt="我真是个天才"></p>
<h1 id="5-最长曼哈顿路径问题"><a href="#5-最长曼哈顿路径问题" class="headerlink" title="5 最长曼哈顿路径问题"></a>5 最长曼哈顿路径问题</h1><h2 id="5-1-问题描述"><a href="#5-1-问题描述" class="headerlink" title="5.1 问题描述"></a>5.1 问题描述</h2><p>LMP(Longest Manhattan Path)</p>
<p>在某一个非负整数构成的$n\times m$矩阵中，找出从左上角通往右下角的一条路径，使得路径总长（沿途所经整数的总和）最大（你只能在矩阵内部向右走或者向下走）</p>
<p><img src="/20190211/ACM动态规划基础篇/p13.png" alt="LMP"></p>
<h2 id="5-2-问题分析"><a href="#5-2-问题分析" class="headerlink" title="5.2 问题分析"></a>5.2 问题分析</h2><h3 id="5-2-1-考虑见神杀神的记忆化搜索"><a href="#5-2-1-考虑见神杀神的记忆化搜索" class="headerlink" title="5.2.1 考虑见神杀神的记忆化搜索"></a>5.2.1 考虑见神杀神的记忆化搜索</h3><p><img src="/20190211/ACM动态规划基础篇/p14.png" alt="记忆化搜索"></p>
<h3 id="5-2-2-考虑一路高歌猛进的动态规划"><a href="#5-2-2-考虑一路高歌猛进的动态规划" class="headerlink" title="5.2.2 考虑一路高歌猛进的动态规划"></a>5.2.2 考虑一路高歌猛进的动态规划</h3><p><img src="/20190211/ACM动态规划基础篇/p15.png" alt="动态规划"></p>
<p>不多赘述</p>
<h1 id="6-小结"><a href="#6-小结" class="headerlink" title="6 小结"></a>6 小结</h1><p>我们发现，递归分治记忆化与动态规划本质上其实相差不多</p>
<p>而相对来说，记忆化搜索会更加好理解一些，而我们的第一反应也大多是记忆化搜索</p>
<p>递归是从最复杂的问题开始，将其分而治之，直到遇到平凡(Trival)的情况，然后一举攻克</p>
<p>而动态规划则是从最简单的情况开始，一层一层的逐步蚕食掉整个问题</p>
<p>我们如何写出动态规划的算法呢</p>
<p>我们将第一反应的从顶向下的递归算法理解，在实现的时候将其颠倒过来，写出一个从底向上的递推转移式</p>
<h1 id="7-最长公共子序列"><a href="#7-最长公共子序列" class="headerlink" title="7 最长公共子序列"></a>7 最长公共子序列</h1><h2 id="7-1-问题描述"><a href="#7-1-问题描述" class="headerlink" title="7.1 问题描述"></a>7.1 问题描述</h2><p>LCS(Longest Common Subsequnce)</p>
<p>给定两个字符串，问两个字符串的公共子序列中，最长的长度为多少？是哪个？</p>
<h3 id="7-1-1-子串-Substring"><a href="#7-1-1-子串-Substring" class="headerlink" title="7.1.1 子串 $Substring$"></a>7.1.1 子串 $Substring$</h3><p>原串中连续的一部分</p>
<h3 id="7-1-2-子序列-Subsequnce"><a href="#7-1-2-子序列-Subsequnce" class="headerlink" title="7.1.2 子序列 $Subsequnce$"></a>7.1.2 子序列 $Subsequnce$</h3><p>原串中任意抽出任意多个字符（可以不连续，但先后顺序不能变），组成的字符串</p>
<h3 id="7-1-3-举个栗子"><a href="#7-1-3-举个栗子" class="headerlink" title="7.1.3 举个栗子"></a>7.1.3 举个栗子</h3><p><img src="/20190211/ACM动态规划基础篇/p16.png" alt="举个栗子"></p>
<p>在串$NorthEastNormalUniversity$中</p>
<p>$East, tNor, Univers$为其子串</p>
<p>$NENU, oo, ttt, htly$为其子序列</p>
<h2 id="7-2-样例及其分析"><a href="#7-2-样例及其分析" class="headerlink" title="7.2 样例及其分析"></a>7.2 样例及其分析</h2><p><img src="/20190211/ACM动态规划基础篇/p17.png" alt="Example"></p>
<h2 id="7-3-解决问题"><a href="#7-3-解决问题" class="headerlink" title="7.3 解决问题"></a>7.3 解决问题</h2><h3 id="7-3-1-相同则减而治之"><a href="#7-3-1-相同则减而治之" class="headerlink" title="7.3.1 相同则减而治之"></a>7.3.1 相同则减而治之</h3><script type="math/tex; mode=display">s1[i] == s2[j]</script><p><img src="/20190211/ACM动态规划基础篇/p18.png" alt="相同则减而治之"></p>
<h3 id="7-3-2-不同则分而治之"><a href="#7-3-2-不同则分而治之" class="headerlink" title="7.3.2 不同则分而治之"></a>7.3.2 不同则分而治之</h3><script type="math/tex; mode=display">s1[i] != s2[j]</script><p><img src="/20190211/ACM动态规划基础篇/p19.png" alt="不同则分而治之"></p>
<h2 id="7-4-转移方程"><a href="#7-4-转移方程" class="headerlink" title="7.4 转移方程"></a>7.4 转移方程</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">scanf</span>(<span class="string">"%s"</span>, a + <span class="number">1</span>);</span><br><span class="line"><span class="built_in">scanf</span>(<span class="string">"%s"</span>, a + <span class="number">1</span>);</span><br><span class="line"><span class="keyword">int</span> la = <span class="built_in">strlen</span>(a + <span class="number">1</span>);</span><br><span class="line"><span class="keyword">int</span> lb = <span class="built_in">strlen</span>(b + <span class="number">1</span>);</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= la; ++i)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= lb; ++j)&#123;</span><br><span class="line">        <span class="keyword">if</span>(a[i] == b[j]) dp[i][j] = dp[i - <span class="number">1</span>][j - <span class="number">1</span>] + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">else</span> dp[i][j] = max(dp[i - <span class="number">1</span>][j], dp[i][j - <span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="7-5-dp表"><a href="#7-5-dp表" class="headerlink" title="7.5 dp表"></a>7.5 dp表</h2><p><img src="/20190211/ACM动态规划基础篇/p20.png" alt="dp表"></p>
<h2 id="7-6-思考题"><a href="#7-6-思考题" class="headerlink" title="7.6 思考题"></a>7.6 思考题</h2><p>如何输出公共最长子序列的内容，以及统计最长公共子序列的个数</p>
<p>（一般来说，寻找长度之类的问题比较容易，追溯解就会比较难搞）<br>（一般来说，寻找任一最优解比较容易，最优解计数问题比较难搞）</p>
<h1 id="8-背包问题（推荐-背包九讲）"><a href="#8-背包问题（推荐-背包九讲）" class="headerlink" title="8  背包问题（推荐 背包九讲）"></a>8  背包问题（推荐 背包九讲）</h1><p>当前你有一个背包，有一系列的物品，物品都有自己的数量、重量$w[i]$以及价值$v[i]$，请问在不超过背包总重量$W$的情况下获得的最大价值是多少（物品不能切分）</p>
<p><img src="/20190211/ACM动态规划基础篇/p21.png" alt="Bag"></p>
<p>考虑贪心：</p>
<ul>
<li><p>优先选择重量最小的</p>
</li>
<li><p>优先选择重量最大的</p>
</li>
<li><p>优先选择单位重量价值最高的</p>
</li>
</ul>
<p><img src="/20190211/ACM动态规划基础篇/p22.png" alt="反例"></p>
<p>都很容易举出反例来</p>
<h2 id="8-1-01背包问题"><a href="#8-1-01背包问题" class="headerlink" title="8.1 01背包问题"></a>8.1 01背包问题</h2><p>所有物品的数量都为1</p>
<h3 id="8-1-1-选还是不选，这是一个问题"><a href="#8-1-1-选还是不选，这是一个问题" class="headerlink" title="8.1.1 选还是不选，这是一个问题"></a>8.1.1 选还是不选，这是一个问题</h3><p>考虑动态规划，用数组$dp[i][j]$表示只考虑前$i$个物品，背包总承重为$j$的情况下，能获得的最大价值</p>
<h3 id="8-1-2-分析转移方程"><a href="#8-1-2-分析转移方程" class="headerlink" title="8.1.2 分析转移方程"></a>8.1.2 分析转移方程</h3><p>对于每个物品我们都有两种情况</p>
<ul>
<li><p>选：获得的最大价值为$dp[i - 1][j - w[i]] + v[i]$</p>
</li>
<li><p>不选：获得的最大价值为$dp[i - 1][j]$</p>
</li>
</ul>
<p>这样的话，我们便很容易得到转移方程</p>
<script type="math/tex; mode=display">dp[i][j] = \begin{cases}  
dp[i - 1][j] &  j < w[i] \\
max\{dp[i - 1][j], dp[i - 1][j - w[i]] + v[i]\} & j >= w[i]
\end{cases}</script><h3 id="8-1-3-dp表"><a href="#8-1-3-dp表" class="headerlink" title="8.1.3 dp表"></a>8.1.3 dp表</h3><p><img src="/20190211/ACM动态规划基础篇/p23.png" alt="dp表"></p>
<h3 id="8-1-4-代码实现"><a href="#8-1-4-代码实现" class="headerlink" title="8.1.4 代码实现"></a>8.1.4 代码实现</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; ++i)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; w[i]; ++j)&#123;</span><br><span class="line">    	dp[i][j] = dp[i - <span class="number">1</span>][j];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> j = w[i]; j &lt;= W; ++j)&#123;</span><br><span class="line">        dp[i][j] = max(dp[i - <span class="number">1</span>][j], dp[i - <span class="number">1</span>][j - w[i]] + v[i]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>优化空间</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; ++i)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> j = W; j &gt;= w[i]; --j)&#123;</span><br><span class="line">        dp[j] = max(dp[j], dp[j - w[i]] + v[i]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意第二层循环顺序为倒序，因为每个物品只有一个，如果正序更新的话会出现当前物品多次选择的情况</p>
<h2 id="8-2-完全背包问题"><a href="#8-2-完全背包问题" class="headerlink" title="8.2 完全背包问题"></a>8.2 完全背包问题</h2><p>所有物品的数量都为无限多个</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; ++i)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> j = w[i]; j &lt;= W; ++j)&#123;</span><br><span class="line">        dp[j] = max(dp[j], dp[j - w[i]] + v[i]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="8-3-多重背包问题"><a href="#8-3-多重背包问题" class="headerlink" title="8.3 多重背包问题"></a>8.3 多重背包问题</h2><p>数量不定</p>
<p>需要考虑二进制优化</p>
<h1 id="9-最长不降子序列LIS"><a href="#9-最长不降子序列LIS" class="headerlink" title="9 最长不降子序列LIS"></a>9 最长不降子序列LIS</h1><h2 id="9-1-定义"><a href="#9-1-定义" class="headerlink" title="9.1 定义"></a>9.1 定义</h2><p>设有一个正整数序列$a[n]: a<em>1, a_2 \cdots, a_n$对于下标$i_1&lt;i_2 &lt; \cdots&lt;i_h$，若有$a</em>{i<em>1}, a</em>{i<em>2} \cdots a</em>{i_h}$,</p>
<p>则称序列$a[n]$含有一个长度为$h$的不下降子序列。</p>
<p>例如，对于序列$3, 7, 9, 16, 38, 24, 27, 38, 44, 49, 21, 52, 63, 15$</p>
<p>对于下标 $i_1 = 1, i_2 = 4, i_3 = 5, i_4 = 9, i_5 = 13$</p>
<p>满足$13 &lt; 16 &lt; 38 &lt; 44 &lt; 63$</p>
<p>则存在长度为5的不下降子序列。</p>
<h2 id="9-2-问题描述"><a href="#9-2-问题描述" class="headerlink" title="9.2 问题描述"></a>9.2 问题描述</h2><p>当给定序列$a_1, a_2 \cdots a_n$后，请求出最长的不下降序列的长度</p>
<h2 id="9-3-解决问题"><a href="#9-3-解决问题" class="headerlink" title="9.3 解决问题"></a>9.3 解决问题</h2><h3 id="9-3-1-O-n-2-的算法"><a href="#9-3-1-O-n-2-的算法" class="headerlink" title="9.3.1 $O(n^2)$的算法"></a>9.3.1 $O(n^2)$的算法</h3><p>对于任意的$i$,  定义$dp[i]$是以$a_i$结束的最长不下降子序列的长度，那么显然，问题的解为$dp[n]$。</p>
<p>不妨假设，已求得以$a<em>1,a_2, \cdots, a</em>{j − 1}$结束的最长不下降子序列的长度分别为$dp[1],dp[2],…,dp[j−1]$</p>
<p>其中$dp[1]=1$</p>
<p>那么对于$a_i$，其中$i &lt; j − 1$,  若 $a_i \le a_j$，则以$a_j$结束的不下降子序列长度为的$dp[i] + 1$</p>
<p>显然以$a_j$结束的最长不下降子序列的长度</p>
<p>$dp[j] = max{dp[i]} + 1$</p>
<p>其中$1 \le i \le j − 1, a_i \le a_j$</p>
<p>更新公式中每次都得从头遍历整个$dp[i]$，所以算法复杂度为$O(n^2)$</p>
<h3 id="9-3-2-O-nlogn-算法"><a href="#9-3-2-O-nlogn-算法" class="headerlink" title="9.3.2 $O(nlogn)$算法"></a>9.3.2 $O(nlogn)$算法</h3><p>$O(nlogn)$的算法关键是它建立了一个数组$b[]$</p>
<p>$b[i]$表示长度为$i$的不下降序列中结尾元素的最小值</p>
<p>用$k$表示数组目前的长度</p>
<p>算法完成后$k$的值即为最长不下降子序列的长度。</p>
<p>不妨假设，当前已求出的长度为$k$</p>
<p>则判断$a[i]$和$b[k]$：</p>
<p>如果$b[k]\le a[i]$，即$a[i]$大于长度为$k$的序列中的最后一个元素</p>
<p>这样就可以使序列的长度增加$1$，即$k = k + 1$ 然后更新$b[k] = a[i]$；</p>
<p>如果$b[k] \gt a[i]$</p>
<p>那么就在$b[1]\cdots b[k]$中找到最大的$j$使得$b[j] &lt; a[i]$，即$a[i]$大于长度为$j$的序列的最后一个元素</p>
<p>显然，$b[j+1] \ge a[i]$， 那么就可以更新长度为$j + 1$的序列的最后一个元素，即$b[j + 1] = a[i]$。</p>
<p>可以注意到：$b[i]$单调递增，很容易理解，长度更长了，$d[k]$的值是不会减小的，因此更新公式可以用二分查找，所以算法复杂度为$O(nlogn)$。</p>
<p>代码实现</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> maxn = <span class="number">5e4</span> + <span class="number">10</span>;</span><br><span class="line"><span class="keyword">int</span> a[maxn], b[maxn];</span><br><span class="line"><span class="comment">//用二分查找的方法找到一个位置，使得x&gt;b[i - 1],并且x&lt;b[i],并用x代替b[i]</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">src</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> l, <span class="keyword">int</span> r)</span></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(l &lt;= r)&#123;</span><br><span class="line">        <span class="keyword">int</span> mid = (l + r)/<span class="number">2</span>;</span><br><span class="line">        <span class="keyword">if</span>(x &gt;= b[mid]) l = mid + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">else</span> r = mid - <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> l;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">dp</span><span class="params">(<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    b[<span class="number">1</span>] = a[<span class="number">1</span>];</span><br><span class="line">    <span class="keyword">int</span> len = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">2</span>; i &lt;= n; ++i)&#123;</span><br><span class="line">        <span class="keyword">if</span>(a[i] &gt;= b[len]) b[++len] = a[i]; <span class="comment">//如果a[i]比b数组中最大的数还大，便将此数直接插入到b数组后面</span></span><br><span class="line">        <span class="keyword">else</span> b[src(a[i], <span class="number">1</span>, len)] = a[i]; <span class="comment">//二分查找第一个比a[i]大的位置并且让a[i]代替这个位置</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> len;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ACM/" rel="tag"># ACM</a>
          
            <a href="/tags/动态规划/" rel="tag"># 动态规划</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/20190211/20190206-新生培训期末总结-题解/" rel="next" title="20190206 新生培训期末总结 题解">
                <i class="fa fa-chevron-left"></i> 20190206 新生培训期末总结 题解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/20190211/康托展开与逆康托展开/" rel="prev" title="康托展开与逆康托展开">
                康托展开与逆康托展开 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/star.jpg" alt="linxi">
            
              <p class="site-author-name" itemprop="name">linxi</p>
              <p class="site-description motion-element" itemprop="description">stay hungry, stay foolish</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.csdn.net/linxilinxilinxi" title="https://blog.csdn.net/linxilinxilinxi" rel="noopener" target="_blank">My CSDN</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-前言"><span class="nav-number">1.</span> <span class="nav-text">1 前言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-什么是动态规划"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 什么是动态规划</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-什么时候要用动态规划"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 什么时候要用动态规划</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-斐波那契数列-Fibonacci"><span class="nav-number">2.</span> <span class="nav-text">2 斐波那契数列 $Fibonacci$</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-引入"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 引入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-定义"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-递归分治解决-Recursion"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 递归分治解决 $Recursion$</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-1-代码"><span class="nav-number">2.3.1.</span> <span class="nav-text">2.3.1 代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-2-时间复杂度分析"><span class="nav-number">2.3.2.</span> <span class="nav-text">2.3.2 时间复杂度分析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-解决方案"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 解决方案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-5-记忆化搜索"><span class="nav-number">2.5.</span> <span class="nav-text">2.5 记忆化搜索</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-快速幂"><span class="nav-number">3.</span> <span class="nav-text">3 快速幂</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-问题描述"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 问题描述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-十进制快速幂"><span class="nav-number">3.2.</span> <span class="nav-text">3.2 十进制快速幂</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-二进制快速幂"><span class="nav-number">3.3.</span> <span class="nav-text">3.3 二进制快速幂</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-4-代码实现"><span class="nav-number">3.4.</span> <span class="nav-text">3.4 代码实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-最短向上路径问题"><span class="nav-number">4.</span> <span class="nav-text">4 最短向上路径问题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-问题描述"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 问题描述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-暴力？"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 暴力？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-递归分治VS动态规划"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 递归分治VS动态规划</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-1-递归分治"><span class="nav-number">4.3.1.</span> <span class="nav-text">4.3.1 递归分治</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-1-时间复杂度"><span class="nav-number">4.3.1.1.</span> <span class="nav-text">4.3.1.1 时间复杂度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-2-记忆化搜索"><span class="nav-number">4.3.1.2.</span> <span class="nav-text">4.3.1.2 记忆化搜索</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-2-正儿八经的动态规划"><span class="nav-number">4.3.2.</span> <span class="nav-text">4.3.2 正儿八经的动态规划</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-1-记忆化？"><span class="nav-number">4.3.2.1.</span> <span class="nav-text">4.3.2.1 记忆化？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-2-动态规划"><span class="nav-number">4.3.2.2.</span> <span class="nav-text">4.3.2.2 动态规划</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-最长曼哈顿路径问题"><span class="nav-number">5.</span> <span class="nav-text">5 最长曼哈顿路径问题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-问题描述"><span class="nav-number">5.1.</span> <span class="nav-text">5.1 问题描述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-问题分析"><span class="nav-number">5.2.</span> <span class="nav-text">5.2 问题分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-1-考虑见神杀神的记忆化搜索"><span class="nav-number">5.2.1.</span> <span class="nav-text">5.2.1 考虑见神杀神的记忆化搜索</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-2-考虑一路高歌猛进的动态规划"><span class="nav-number">5.2.2.</span> <span class="nav-text">5.2.2 考虑一路高歌猛进的动态规划</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-小结"><span class="nav-number">6.</span> <span class="nav-text">6 小结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-最长公共子序列"><span class="nav-number">7.</span> <span class="nav-text">7 最长公共子序列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-1-问题描述"><span class="nav-number">7.1.</span> <span class="nav-text">7.1 问题描述</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1-1-子串-Substring"><span class="nav-number">7.1.1.</span> <span class="nav-text">7.1.1 子串 $Substring$</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1-2-子序列-Subsequnce"><span class="nav-number">7.1.2.</span> <span class="nav-text">7.1.2 子序列 $Subsequnce$</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1-3-举个栗子"><span class="nav-number">7.1.3.</span> <span class="nav-text">7.1.3 举个栗子</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-2-样例及其分析"><span class="nav-number">7.2.</span> <span class="nav-text">7.2 样例及其分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-3-解决问题"><span class="nav-number">7.3.</span> <span class="nav-text">7.3 解决问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#7-3-1-相同则减而治之"><span class="nav-number">7.3.1.</span> <span class="nav-text">7.3.1 相同则减而治之</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-3-2-不同则分而治之"><span class="nav-number">7.3.2.</span> <span class="nav-text">7.3.2 不同则分而治之</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-4-转移方程"><span class="nav-number">7.4.</span> <span class="nav-text">7.4 转移方程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-5-dp表"><span class="nav-number">7.5.</span> <span class="nav-text">7.5 dp表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-6-思考题"><span class="nav-number">7.6.</span> <span class="nav-text">7.6 思考题</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#8-背包问题（推荐-背包九讲）"><span class="nav-number">8.</span> <span class="nav-text">8  背包问题（推荐 背包九讲）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#8-1-01背包问题"><span class="nav-number">8.1.</span> <span class="nav-text">8.1 01背包问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#8-1-1-选还是不选，这是一个问题"><span class="nav-number">8.1.1.</span> <span class="nav-text">8.1.1 选还是不选，这是一个问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-1-2-分析转移方程"><span class="nav-number">8.1.2.</span> <span class="nav-text">8.1.2 分析转移方程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-1-3-dp表"><span class="nav-number">8.1.3.</span> <span class="nav-text">8.1.3 dp表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-1-4-代码实现"><span class="nav-number">8.1.4.</span> <span class="nav-text">8.1.4 代码实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-2-完全背包问题"><span class="nav-number">8.2.</span> <span class="nav-text">8.2 完全背包问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-3-多重背包问题"><span class="nav-number">8.3.</span> <span class="nav-text">8.3 多重背包问题</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#9-最长不降子序列LIS"><span class="nav-number">9.</span> <span class="nav-text">9 最长不降子序列LIS</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#9-1-定义"><span class="nav-number">9.1.</span> <span class="nav-text">9.1 定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-2-问题描述"><span class="nav-number">9.2.</span> <span class="nav-text">9.2 问题描述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-3-解决问题"><span class="nav-number">9.3.</span> <span class="nav-text">9.3 解决问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#9-3-1-O-n-2-的算法"><span class="nav-number">9.3.1.</span> <span class="nav-text">9.3.1 $O(n^2)$的算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#9-3-2-O-nlogn-算法"><span class="nav-number">9.3.2.</span> <span class="nav-text">9.3.2 $O(nlogn)$算法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">linxi</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.0.0</div>





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">全站共 65.5k 字</span>
</div>

        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  
    
    
  
  <script color="25,202,173" opacity="0.8" zindex="-1" count="200" src="/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.0"></script>

  <script src="/js/src/motion.js?v=7.0.0"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.0"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.0"></script>



  
  <script src="/js/src/scrollspy.js?v=7.0.0"></script>
<script src="/js/src/post-details.js?v=7.0.0"></script>



  


  <script src="/js/src/bootstrap.js?v=7.0.0"></script>



  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'LwzdQrGG81bUwkUkAfdPexj1-gzGzoHsz',
    appKey: 'akTaTqH7XeeKc6CPRfB7vbDl',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false
  });
</script>




  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log(`Failed to save Visitor num, with error message: ${responseJSON.error}`);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log(`LeanCloud Counter Error: ${responseJSON.code} ${responseJSON.error}`);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'LwzdQrGG81bUwkUkAfdPexj1-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'LwzdQrGG81bUwkUkAfdPexj1-gzGzoHsz',
                'X-LC-Key': 'akTaTqH7XeeKc6CPRfB7vbDl',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: "AMS"
      }
    }
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
      for (i = 0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>
<script src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

<style>
.MathJax_Display {
  overflow: auto hidden;
}
</style>

    
  


  

  

  

  

  

  

  

  

  

  

</body>
</html>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

